package larpplanner.gui;

import java.util.Arrays;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;

public class MyAutoComplete extends Composite{

	private Combo combo;
	private String[] superItems;
	private String[] items;
	private int limit;
	private String txt = "";
	private boolean once = true;
	
	public MyAutoComplete(Composite parent, String[] items_a, int limit) {
		super(parent, SWT.NONE);
		combo = new Combo(parent, SWT.SIMPLE);
		this.limit = limit;
		superItems = items_a;
		Arrays.sort(superItems);
		items = new String[limit];
		updateItems();
		
		combo.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				if(once){
					txt = combo.getText();
					updateItems();
					once = false;
				}else
					once = true;
			}
		});
		
		combo.addKeyListener(new KeyAdapter() {
			public void keyPressed(KeyEvent e) {
				e.doit = false;
				if(e.keyCode == 8){
					if(txt.length() > 0)
						txt = txt.substring(0,txt.length()-1);
				}else
					txt += (char)e.keyCode;
				updateItems();
			}
		});
	}

	private void updateItems() {
		int idx = 0;
		if(!txt.equals("")){
			while(idx < superItems.length) {
				String superItemsTxt = superItems[idx].substring(0, Math.min(txt.length(),superItems[idx].length()));
				if(superItemsTxt.equals(txt))
					break;
				idx++;
			}
		}
		items = Arrays.copyOfRange(superItems, idx, Math.min(idx + limit, superItems.length));
		combo.setItems(items);
		combo.setText(txt);
	}
}